/**
 * 最后访问地址
 */
var userLastUrl = typeof localStorage.userLastUrl == 'undefined' || localStorage.userLastUrl == 'null' || localStorage.userLastUrl == null  ? index_url('user/index') : localStorage.userLastUrl;
if (location.href.indexOf('login') == -1) {
    localStorage.userLastUrl = location.href;
}

/**
 * 用户信息
 */
var userInfo = typeof localStorage.userInfo == 'undefined' || localStorage.userInfo == 'null' || localStorage.userInfo == null  ? {} : JSON.parse(localStorage.userInfo);

/**
 * 重新获取用户信息
 */
function userTokenInfo() {
    post('api/user/tokenInfo', {token: userInfo.token}, function (res){
        if (res.status === 'success') {
            localStorage.userInfo = JSON.stringify(res.data);
            userInfo = res.data;
        }
    })
}

/**
 * 发送post请求
 * @param  {String} link   链接
 * @param  {Object} data  数据集
 */
function post(link, data, callback = ""){
    // 带上token
    data.token = userInfo.token;
	$.ajax({
		url: index_url(link),
		type: 'post',
		dataTyle: 'json',
		contentType:"application/json;charset=utf-8",
		data: JSON.stringify(data),
		success:function(res) {
			var res = typeof res == 'string' ? JSON.parse(res) : res;
			if (res.status === 'login') {
				location.href = index_url("login/index");
			} else {
				if (callback != "") callback(res);
			}
		},
		error:function(res) {
			res.status  = 'error';
			res.message = res.statusText;
			if (callback != "") callback(res);
		}
	})
}

/**
 * 获取链接信息
 */
var locationUrl = {
	/**
	 * 获取链接参数
	 * @param  {String} name 参数名
	 */
	get(name) {
	    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	    var u = decodeURI(window.location.search.substr(1));
	    var r = u.match(reg); 
	    if (r != null) return unescape(r[2]); 
	    return "";
	},
	/**
	 * 设置链接参数
	 * @param  {String} name  参数名
	 * @param  {String} value 值
	 */
	set(name, value){
		var loadUrl = location.href;
		var arrUrl  = loadUrl.split('#');
		var url     = arrUrl[0];
		var pattern = name + '=([^&]*)';
	    var replaceText = name+'='+value; 
	    var newUrl = "";
	    if (url.match(pattern)) {
	        var tmp = '/(' + name + '=)([^&]*)/gi';
	        newUrl = url.replace(eval(tmp),replaceText);
	    } else { 
	        if (url.match('[\?]')) { 
	            newUrl = url + '&' + replaceText; 
	        } else {
	            newUrl =  url +'?' + replaceText; 
	        } 
	    }
	    location.href = newUrl+window.location.hash
	}
}